//
//  ChangeInforViewCtrl.m
//  MIDI
//
//  Created by 千行时线 on 15/9/15.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "ChangeInforViewCtrl.h"
#import "ChangeIDViewCtrler.h"
#import "ChangeNameViewCtrler.h"

#import "UIViewController+Create.h"
#import "AppConfig.h"
#import "ChanageNationViewCtrler.h"
#import "ChangeInfoCell.h"
#import "APIAdress.h"
#import "QXNetWorkTool.h"
#import "UserDataSingleton.h"
#import "UIImageView+WebCache.h"
#import "CommFunc.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIActionSheet+Blocks.h"
#import "MBProgressHUD+YC.h"
#import "SelfInfoModel.h"

#define MIDIIDFORMAT @"midiID:%s"
@interface ChangeInforViewCtrl ()<UIPickerViewDataSource,UIPickerViewDelegate , UITableViewDataSource , UITableViewDelegate , QXNetWorkToolDelegate , UITextFieldDelegate , UIImagePickerControllerDelegate ,
    UINavigationControllerDelegate >
@property (weak, nonatomic) UIImageView *mainIconUIIamge;
@property (weak, nonatomic) UILabel *midiIdUILabel;
@property (weak, nonatomic) IBOutlet UIView *ChangeHeadMask;
@property (weak, nonatomic) IBOutlet UIView *ChangeHeadBtns;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ChangeHeadBannerBottom;

@property (weak, nonatomic) IBOutlet UIView *ChangeSexMask;
@property (weak, nonatomic) IBOutlet UIView *ChangeSexBtns;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ChangeSexBannerBottom;
@property (weak, nonatomic) IBOutlet UILabel *ChangeSex_WomanUILabel;
@property (weak, nonatomic) IBOutlet UILabel *ChangeSex_ManUILabel;

@property (copy , nonatomic) NSString * imageData;

@property (strong , nonatomic) UIImagePickerController *headPicker;

@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property (assign ,nonatomic) NSInteger curSex;
@property (assign,nonatomic) NSInteger RaceselectIndex;

@property (strong,nonatomic) NSMutableArray * RaceData;

@property (strong , nonatomic) QXNetWorkTool * netTool;

@property (strong , nonatomic) NSMutableDictionary * infoDic;

@property (weak , nonatomic) UITextField *nationField;
@property (weak , nonatomic) UITextField *raceField;

@end

@implementation ChangeInforViewCtrl

- (void)viewDidLoad {
    [super viewDidLoad];

    self.curSex = 1;
    
    self.ChangeHeadBannerBottom.constant = -145;
    self.ChangeHeadMask.hidden = YES;

    self.ChangeSexBannerBottom.constant = -145;
    self.ChangeSexMask.hidden = YES;
    
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.netTool = [[QXNetWorkTool alloc]init];
    self.netTool.QXNetWorkDelegate = self;
    self.imageData = @"";
    self.infoDic = [[NSMutableDictionary alloc]init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//修改头像点击事件
- (void)didClick_changeHeadIcon:(id)sender
{
    [self upLoadHeadphoto];
}

- (void)didClick_Name:(id)sender {
    [self.navigationController pushViewController:[ChangeNameViewCtrler create] animated:YES];
}

- (void)didClick_Sex:(id)sender
{
    if (self.curSex == 1)
    {
        self.ChangeSex_ManUILabel.textColor = [UIColor blackColor];
        self.ChangeSex_WomanUILabel.textColor = UIColorRGBA(19, 208, 202, 1);
    }
    else
    {
        self.ChangeSex_WomanUILabel.textColor = [UIColor blackColor];
        self.ChangeSex_ManUILabel.textColor = UIColorRGBA(19, 208, 202, 1);
    }
    
    
    self.ChangeSexBannerBottom.constant = -145;
    self.ChangeSexMask.hidden = NO;
    [UIView animateWithDuration:0.3	 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGFloat offsetY = [UIScreen mainScreen].bounds.size.height -145;
        CGRect orgRec = self.ChangeSexBtns.frame;
        self.ChangeSexBtns.frame = CGRectMake(orgRec.origin.x , offsetY, orgRec.size.width, orgRec.size.height);
        
    } completion:^(BOOL finished) {
        self.ChangeSexBannerBottom.constant = 0;
        self.ChangeSexMask.hidden = NO;
        
    }];
}
- (void)didClick_Contry:(id)sender
{
    [self.navigationController pushViewController:[ChanageNationViewCtrler create] animated:YES];
}
- (void)didClick_Race:(id)sender {

}
- (void)didClick_Birth:(id)sender
{
    
}
- (void)didClick_ID:(id)sender {
    [self.navigationController pushViewController:[ChangeIDViewCtrler create] animated:YES];
}

#pragma mark ChangeSex
- (IBAction)didClick_ChangeSexMan:(id)sender
{
    self.curSex = 1;
    self.ChangeSex_ManUILabel.textColor = [UIColor blackColor];
    self.ChangeSex_WomanUILabel.textColor = UIColorRGBA(19, 208, 202, 1);
}

- (IBAction)didClick_ChangeSexWoman:(id)sender
{
    self.curSex = 2;
    self.ChangeSex_WomanUILabel.textColor = [UIColor blackColor];
    self.ChangeSex_ManUILabel.textColor = UIColorRGBA(19, 208, 202, 1);
}
- (IBAction)didClick_ChangeSexSave:(id)sender
{
    self.ChangeSexBannerBottom.constant = 0;
    self.ChangeSexMask.hidden = NO;
    [UIView animateWithDuration:0.3	 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGFloat offsetY = [UIScreen mainScreen].bounds.size.height +145;
        CGRect orgRec = self.ChangeSexBtns.frame;
        self.ChangeSexBtns.frame = CGRectMake(orgRec.origin.x , offsetY, orgRec.size.width, orgRec.size.height);
        
    } completion:^(BOOL finished) {
        self.ChangeSexBannerBottom.constant = -145;
        self.ChangeSexMask.hidden = YES;
        
    }];
}

#pragma mark ChangeHeadIcon

- (IBAction)didClick_changeHeadPhoto:(id)sender {
}

- (IBAction)didClick_changeHeadChosePhotoLocal:(id)sender {
}

- (IBAction)didClick_changeHeadCancel:(id)sender
{
    self.ChangeHeadBannerBottom.constant = 0;
    self.ChangeHeadMask.hidden = NO;
    [UIView animateWithDuration:0.3	 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGFloat offsetY = [UIScreen mainScreen].bounds.size.height +145;
        CGRect orgRec = self.ChangeHeadBtns.frame;
        self.ChangeHeadBtns.frame = CGRectMake(orgRec.origin.x , offsetY, orgRec.size.width, orgRec.size.height);
        
    } completion:^(BOOL finished) {
        self.ChangeHeadBannerBottom.constant = -145;
        self.ChangeHeadMask.hidden = YES;
        
    }];
}
#pragma mark ChangeRace
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 10;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return [UIScreen mainScreen].bounds.size.width;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.RaceselectIndex = row;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont fontWithName:@"Hiragino Sans GB" size:18]];
        pickerLabel.textColor = [UIColor blackColor];
        [pickerLabel setText:@"hello"];
    }
    return pickerLabel;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
}


-(void) configNavigationItem
{
    [self.tabBarController configNavigationBarTintColor:UIColorRGBA(0, 0, 0, 1)];
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"完善个人信息";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    UIButton *barButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 15)];
    //    [self configNavigationRightString:@"筛选" textFont:[UIFont fontWithName:@"Hiragino Sans GB" size:13] andAction:^{[self pressRight];}];
    
    [self configNavigationBackAction:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(clickSave:)];
    UIFont *rightFont = [UIFont fontWithName:@"Hiragino Sans GB" size:13.0];
    UIColor *rightColor = UIColorRGBA(19, 208, 202, 1);
    
    NSDictionary * attributes = @{NSFontAttributeName:rightFont , NSForegroundColorAttributeName:rightColor };
    [rightBar setTitleTextAttributes:attributes forState:UIControlStateNormal];
    [self.navigationItem setRightBarButtonItem:rightBar];
}

-(void)clickSave:(id)sender
{
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    NSMutableDictionary * dic = self.infoDic;
    [dic removeAllObjects];
    
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    
    [dic setValue:userdata.real_name forKey:@"real_name"];
    [dic setValue:userdata.user_id forKey:@"user_id"];
    [dic setValue:userdata.nickname forKey:@"nickname"];
    [dic setValue:userdata.eamil forKey:@"eamil"];
    [dic setValue:userdata.id_card forKey:@"id_card"];
    [dic setValue:userdata.province forKey:@"province"];
    [dic setValue:userdata.curCityId forKey:@"city"];
    [dic setValue:userdata.phone forKey:@"phone"];
    [dic setValue:self.nationField.text forKey:@"nationality"];
    [dic setValue:userdata.sex forKey:@"sex"];
    [dic setValue:userdata.birthday forKey:@"birthday"];
    [dic setValue:self.raceField.text forKey:@"people"];
    NSString *imgdata = self.imageData;
    if(imgdata == nil || [imgdata isEqual:@""])
    {
        imgdata = userdata.head_img;
    }
    [dic setValue:imgdata forKey:@"head_img"];
    
    [self.netTool GetDataFromServerWithPostMethodandInterfaceName:FillDetailInterface andParameter:@[dic] tag:1];
}

#pragma mark QxWorkTool ------------------------
-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    if(tag == 1)
    {
        [MBProgressHUD showSuccess:@"保存成功"];
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        userdata.isSelfInfoChange = YES;
        userdata.people = [self.infoDic objectForKey:@"people"];
        userdata.nationality = [self.infoDic objectForKey:@"nationality"];
        
        
        
        [self reqSelfInfo];
    }
    else if(tag == 2)
    {
        SelfInfoModel * data = nil;
        for(NSDictionary * dic in Response)
        {
            data = [SelfInfoModel MyModelWithDict:dic];
            break;
        }
        if(data == nil)
            return;
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        userdata.isGotSelfInfo = YES;
        userdata.midi_id = data.midi_id;
        userdata.sex = data.sex;
        userdata.eamil = data.eamil;
        userdata.people = data.people;
        userdata.nationality = data.nationality;
        userdata.id_card = data.id_card;
        userdata.head_img = data.head_img;
        userdata.nickname = data.nickname;
        userdata.real_name = data.real_name;
        userdata.phone = data.phone;
        userdata.birthday = data.birthday;
        userdata.isSelfInfoChange = NO;
        [self.myTableView reloadData];
    }
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
    
}

#pragma mark InterFace

//点击保存民族
-(void) saveRace:(NSInteger)index
{
    
}


#pragma mark tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 587;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChangeInfoCell * cell = [ChangeInfoCell loadFromXib];
    [self configCell:cell];
    return cell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(void) configCell : (ChangeInfoCell *)cell
{
    self.mainIconUIIamge = cell.icoImageView;
    [self.mainIconUIIamge.layer setCornerRadius:self.mainIconUIIamge.frame.size.width/2];
    self.mainIconUIIamge.clipsToBounds = YES;
    self.mainIconUIIamge.contentMode = UIViewContentModeScaleAspectFill;
    self.midiIdUILabel = cell.nameLb;
    [cell.btnChangeHead addTarget:self action:@selector(didClick_changeHeadIcon:) forControlEvents:UIControlEventTouchUpInside];
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    if([userdata isLogin])
    {
        NSString *headIco = userdata.head_img;
        if(headIco == nil || [headIco isEqual:@""])
        {
            self.mainIconUIIamge.image = [UIImage imageNamed:@"ico_selfinfo_nonoe"];
        }else
        {
            [self.mainIconUIIamge sd_setImageWithURL:[NSURL URLWithString:headIco]];
//            [self.mainIconUIIamge setImage:[[UIImage alloc] initWithData:[CommFunc getDecodedDataFromBase64String:userdata.head_img]]];
        }
        [self.midiIdUILabel setText:[@"midiID: " stringByAppendingString:userdata.midi_id]];
    }
    else
    {
        self.mainIconUIIamge.image = [UIImage imageNamed:@"ico_selfinfo_nonoe"];
        [self.midiIdUILabel setText:@"登陆/注册"];
    }
    if([CommFunc validateIDCardNumber:userdata.id_card])
    {
        NSString *idNum = userdata.id_card;
        NSString *year = nil;
        NSString *month = nil;
        NSString *day = nil;
        NSString *sex = nil;
        if(idNum.length == 15)
        {
            year =[@"19" stringByAppendingString:[idNum substringWithRange:NSMakeRange(6, 2)]];
            month = [idNum substringWithRange:NSMakeRange(8, 2)];
            day = [idNum substringWithRange:NSMakeRange(10, 2)];
            sex = [idNum substringWithRange:NSMakeRange(12, 3)];
        }
        else if(idNum.length == 18)
        {
            year =[idNum substringWithRange:NSMakeRange(6, 4)];
            month = [idNum substringWithRange:NSMakeRange(10, 2)];
            day = [idNum substringWithRange:NSMakeRange(12, 2)];
            sex = [idNum substringWithRange:NSMakeRange(14, 3)];
        }
        if([sex integerValue] %2 ==0)  //判断性别
        {
            [cell.sexLabel setText:@"女"];
        }
        else
        {
            [cell.sexLabel setText:@"男"];
        }
        
        NSString *birthday = [[[[year stringByAppendingString:@"-"] stringByAppendingString:month]stringByAppendingString:@"-"] stringByAppendingString:day];
        [cell.birthDayLabel setText:birthday];
        [cell.idNumberLb setText:idNum];
    }
    else
    {
        [cell.idNumberLb setText:@"未知"];
        [cell.birthDayLabel setText:@"未知"];
        if(userdata.sex != nil && ([userdata.sex isEqual:@"1"] || [userdata.sex isEqual:@"2"]))
        {
            if([userdata.sex isEqual:@"1"])
            {
                [cell.sexLabel setText:@"男"];
            }
            else
            {
                [cell.sexLabel setText:@"女"];
            }
        }else
        {
            [cell.sexLabel setText:@"未知"];
        }
        
    }
    cell.raceFeild.delegate = self;
    cell.countryFeild.delegate = self;
    cell.raceFeild.tag = 1;
    cell.countryFeild.tag = 2;
    self.raceField = cell.raceFeild;
    self.nationField = cell.countryFeild;
}
#pragma mark --------UITextField delegate-----------------------
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField.tag == 1)
    {
        if(textField.text.length <= 0)
            [MBProgressHUD showError:@"请输入正确的名族"];
    }
    else if(textField.tag == 2)
    {
        if(textField.text.length <= 0)
            [MBProgressHUD showError:@"请输入正确的国家"];
    }
}

#pragma nark -------------------upload photo-------------------
-(void)setHead:(UIImage *)image
{
    
    [self.mainIconUIIamge setImage:image];
    self.imageData = [CommFunc getImageBase64String:image];
}

//照相 读取相册
- (void)upLoadHeadphoto
{
    self.headPicker = [[UIImagePickerController alloc] init];
    self.headPicker.mediaTypes = @[(NSString *)kUTTypeImage];
    self.headPicker.allowsEditing = YES;
    self.headPicker.delegate = self;
    
    if (YES/*[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]*/) {
        WEAKSELF
        [UIActionSheet showInView:self.view withTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"拍照", @"从相册选择"] tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
            switch (buttonIndex) {
                case 0:
                    weakSelf.headPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    weakSelf.headPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                default:
                    break;
            }
            if (buttonIndex != actionSheet.cancelButtonIndex) {
                [weakSelf.navigationController presentViewController:weakSelf.headPicker animated:YES completion:nil];
            }
        }];
    }
    else
    {
        self.headPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self.navigationController presentViewController:self.headPicker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if (picker == self.headPicker)
    {
        [picker dismissViewControllerAnimated:YES completion:^{
            
            UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
            
            [self setHead:editedImage];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//请求个人数据
-(void)reqSelfInfo
{
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    [self.netTool GetDataFromServerWithPostMethodandInterfaceName:GetSelfInfoInterface andParameter:@[@{@"user_id":userdata.user_id}] tag:2];
}


@end
